package com.ztk.threadbasic.future;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class Future01 {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        Callable01 callable01 = new Callable01();
        FutureTask futureTask = new FutureTask(callable01);
        Thread thread01 = new Thread(futureTask);
        thread01.start();

        Thread thread = new Thread(() -> {
            try {
                Thread.sleep(10000);
                callable01.setFlag(false);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        thread.start();

        System.out.println("第一次查看任务状态，是否正在执行：" + futureTask.isCancelled());
        Thread.sleep(2000);
        // System.out.println(futureTask.get());
        System.out.println("取消任务");
        futureTask.cancel(false);
        System.out.println("第二次查看任务状态，是否正在执行：" + futureTask.isCancelled());
        Thread.sleep(2000);
        System.out.println("第三次查看任务状态，是否正在执行：" + futureTask.isCancelled());

        System.out.println("任务是否已结束" + futureTask.isDone());

    }
}

class Callable01 implements Callable<Integer> {

    private volatile boolean flag = true;

    @Override
    public Integer call() throws Exception {
        int count = 0;
        System.out.println("开始执行Callable方法");
        while (flag) {
            count++;
            Thread.sleep(1000);
            System.out.println("任务执行中~~");
            System.out.println("验证取消任务是否会等待逻辑执行完：准备取消任务");
            Thread.sleep(2000);
            System.out.println("验证取消任务是否会等待逻辑执行完：任务取消后，本日志是否打印");
        }
        System.out.println("结束执行Callable方法");
        return count;
    }

    public void setFlag(boolean flag) {
        this.flag = flag;
    }
}
